﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;

namespace EnableAuditSettings
{
    class Program
    {
        static void Main(string[] args)
        {
            #region ---- Variables ----
            //Variables with default values
            string[] siteurls=null;
            int auditLogRetentionTrim = 90;                     
            SPAuditMaskType auditMask= SPAuditMaskType.None;
            bool clearExistingAuditSettings = false;
            bool trimAuditLog = false;
            #endregion

            #region ---- Set values from app.config ----
            Console.WriteLine("Reading settings from app.config");
            try
            {
                siteurls = ConfigurationManager.AppSettings["Site"].Split(';');
            }
            catch (Exception ex) { Console.WriteLine("Site: " + ex.Message); Environment.Exit(0); }
            try
            {
                auditLogRetentionTrim = int.Parse(ConfigurationManager.AppSettings["AuditLogRetentionTrim"].ToString());
            }
            catch (Exception ex) { Console.WriteLine("AuditLogRetentionTrim: " + ex.Message); Environment.Exit(0); }
            try
            {
                auditMask = (SPAuditMaskType)Enum.Parse(typeof(SPAuditMaskType),ConfigurationManager.AppSettings["AuditValueToAdd"]);
            }
            catch (Exception ex) { Console.WriteLine("AuditValueToAdd: " + ex.Message);Environment.Exit(0); }
            try
            {
                clearExistingAuditSettings = bool.Parse(ConfigurationManager.AppSettings["ClearAllExistingAuditSettings"]);
            }
            catch (Exception ex) { Console.WriteLine("ClearAllExistingAuditSettings: " + ex.Message); Environment.Exit(0); }
            try
            {
                trimAuditLog = bool.Parse(ConfigurationManager.AppSettings["TrimAuditLog"]);
            }
            catch (Exception ex) { Console.WriteLine("TrimAuditLog: " + ex.Message); Environment.Exit(0); }
            Console.WriteLine("Site(s):                       " + ConfigurationManager.AppSettings["Site"]);
            Console.WriteLine("AuditLogRetentionTrim:         " + auditLogRetentionTrim);
            Console.WriteLine("AuditValueToAdd:               " + ConfigurationManager.AppSettings["AuditValueToAdd"].ToString());
            Console.WriteLine("ClearAllExistingAuditSettings  " + clearExistingAuditSettings.ToString());
            Console.WriteLine("TrimAuditLog:                  " + trimAuditLog.ToString());
            #endregion

            foreach (string siteurl in siteurls)
            {
                Console.WriteLine("site:" + siteurl);
                IterateSites(siteurl, auditMask, auditLogRetentionTrim, clearExistingAuditSettings, trimAuditLog);
            }
        }

        #region ---- Methods -----
        private static void IterateSites(string siteurl, SPAuditMaskType auditMask, int auditLogRetentionTrim, bool clearExistingAuditSettings, bool trimAuditLog)
        {
            SPWebApplication webApp = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    webApp = SPWebApplication.Lookup(new Uri(siteurl));
                    int sitecount = 0;
                    SPSiteCollection siteCollections = webApp.Sites;
                    Console.WriteLine("Total of " + siteCollections.Count +" sites in "+ siteurl);
                    foreach (SPSite site in siteCollections)
                    {
                        try
                        {
                            sitecount++;
                            EnableSiteAuditMask(site, auditMask, auditLogRetentionTrim,clearExistingAuditSettings,trimAuditLog);
                            Console.WriteLine(sitecount + " of " + siteCollections.Count);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error in application: " + ex.Message + " site:" + site.ServerRelativeUrl);
                            continue;
                        }
                        finally
                        {
                            site.Dispose();
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("RunWithElevatedPrivileges error: " + ex.Message + " " + webApp.DisplayName);
            }
            finally
            {
            }
            Console.WriteLine("Done");
        }

        private static void EnableSiteAuditMask(SPSite site,SPAuditMaskType auditMask,int auditLogRetentionTrim,bool clearExistingAuditSettings,bool trimAuditLog)
        {
            if (clearExistingAuditSettings) {
                site.Audit.AuditFlags = auditMask;
            }
            else
            {
                site.Audit.AuditFlags = (site.Audit.AuditFlags | auditMask);
            }
                site.Audit.Update();
                site.TrimAuditLog = trimAuditLog;
                site.AuditLogTrimmingRetention = auditLogRetentionTrim;
        }
        #endregion
    }
}
